﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Bootstrap.Helper
{
    public class ReflectionHelper
    {
        public static void SetProperiesRecursive(object source, object target)
        {
            try
            {
                var targetType = target.GetType();
                var sourceType = source.GetType();
                var sourceProperties = source.GetType().GetProperties();

                foreach (PropertyInfo sourcePropertiesItem in sourceProperties)
                {
                    var targetProperty = targetType.GetProperty(sourcePropertiesItem.Name);

                    if (targetProperty != null)
                    {
                        var value = sourcePropertiesItem.GetValue(source, null);

                        if (sourcePropertiesItem.PropertyType.IsArray)
                        {
                            var sourcePropertiesItemValueArray = (value as object[]);
                            var valueResponseListArray = Array.CreateInstance(targetProperty.PropertyType.GetElementType(), sourcePropertiesItemValueArray.Length);

                            for (int i = 0; i < sourcePropertiesItemValueArray.Length; i++)
                            {
                                var instance = Activator.CreateInstance(targetProperty.PropertyType.GetElementType(), null);

                                SetProperiesRecursive(sourcePropertiesItemValueArray[i], instance);
                                valueResponseListArray.SetValue(instance, i);
                            }

                            targetProperty.SetValue(target, valueResponseListArray, null);
                        }
                        else
                        {
                            var propertyValue = Convert.ChangeType(value, targetProperty.PropertyType);

                            targetProperty.SetValue(target, propertyValue, null);
                        }
                    }
                }
            }


            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
